#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "GameModel.h"
#include <QPainter>
#include <QMouseEvent>
#include <math.h>
#include <QMessageBox>
#include <QTimer>
#include <time.h>
#include <stdlib.h>
#include <QApplication>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QMenuBar>
#include <QStatusBar>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //setMouseTracking(true);
    setupUI();
    setupMenuBar();
    setupStatusBar();

    //设置窗口大小
    setFixedSize(MARGIN * 2 + BLOCK_SIZE * BOARD_GRAD_SIZE,MARGIN * 2 + BLOCK_SIZE * BOARD_GRAD_SIZE);

    initGame();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setupUI() {
    setWindowTitle("五子棋");
    resize(800, 600);

    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);

    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);

    titleLabel = new QLabel("五子棋游戏", this);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; margin-bottom: 20px;");
    mainLayout->addWidget(titleLabel);

    QGridLayout *buttonLayout = new QGridLayout();
    mainLayout->addLayout(buttonLayout);

    humanVsAIButton = new QPushButton("人机对战", this);
    humanVsHumanButton = new QPushButton("玩家对战", this);
    settingsButton = new QPushButton("游戏设置", this);
    helpButton = new QPushButton("帮助", this);

    buttonLayout->addWidget(humanVsAIButton, 0, 0);
    humanVsAIButton->setFixedSize(200,100);
    buttonLayout->addWidget(humanVsHumanButton, 0, 1);
    humanVsHumanButton->setFixedSize(200,100);
    buttonLayout->addWidget(settingsButton, 1, 0);
    settingsButton->setFixedSize(200,100);
    buttonLayout->addWidget(helpButton, 1, 1);
    helpButton->setFixedSize(200,100);

    connect(humanVsAIButton, &QPushButton::clicked, this, &MainWindow::onHumanVsAIButtonClicked);
    connect(humanVsHumanButton, &QPushButton::clicked, this, &MainWindow::onHumanVsHumanButtonClicked);
    connect(settingsButton, &QPushButton::clicked, this, &MainWindow::onSettingsButtonClicked);
    connect(helpButton, &QPushButton::clicked, this, &MainWindow::onHelpButtonClicked);
}

void MainWindow::setupMenuBar() {
    QMenu *fileMenu = menuBar()->addMenu("文件");
    QAction *exitAction = fileMenu->addAction("退出");
    connect(exitAction, &QAction::triggered, this, &MainWindow::close);

    QMenu *helpMenu = menuBar()->addMenu("帮助");
    QAction *aboutAction = helpMenu->addAction("关于");
    connect(aboutAction, &QAction::triggered, this, &MainWindow::onAboutActionTriggered);

    QAction *newGameAction = menuBar()->addAction("重新开始");
    connect(newGameAction, &QAction::triggered, this, &MainWindow::onNewGameActionTriggered);
}

void MainWindow::initGame()
{
    //初始化游戏模型
    game = new GameModel;
    // 根据当前模式重新初始化游戏
    if (game_type == AI)
    {
        initAIGame();
    }
    else
    {
        initHumanVsHumanGame();
    }
}

void MainWindow::initHumanVsHumanGame() {
    game_type = MAN; // 设置游戏模式为玩家对战
    game->gameStatus = PLAYING;
    game->startGame(game_type); // 初始化游戏
    update(); // 重新绘制棋盘
}

void MainWindow::initAIGame()
{
    game_type = AI;
    game->gameStatus = PLAYING;

    //在数据模型中进行初始化功能
    game->startGame(game_type);
    update();
}

void MainWindow::setupStatusBar() {
    statusBar()->showMessage("欢迎来到五子棋游戏", 3000);
}

void MainWindow::onHumanVsAIButtonClicked() {
    QMessageBox::information(this, "游戏模式", "您选择了人机对战模式！");
    // 隐藏主界面的按钮
    humanVsAIButton->hide();
    humanVsHumanButton->hide();
    settingsButton->hide();
    helpButton->hide();
    titleLabel->hide();
    initAIGame();// 初始化人机对战模式
}

void MainWindow::onHumanVsHumanButtonClicked() {
    QMessageBox::information(this, "游戏模式", "您选择了玩家对战模式！");
    // 隐藏主界面的按钮
    humanVsAIButton->hide();
    humanVsHumanButton->hide();
    settingsButton->hide();
    helpButton->hide();
    titleLabel->hide();
    initHumanVsHumanGame(); // 初始化玩家对战模式
}

void MainWindow::onSettingsButtonClicked() {
    QMessageBox::information(this, "游戏设置", "打开游戏设置窗口！");
    if (!settingsWindow) {
        settingsWindow = new SettingsWindow(this);
    }
    settingsWindow->exec(); // 以模态方式打开设置窗口
}

void MainWindow::onHelpButtonClicked() {
    QMessageBox::information(this, "帮助", "五子棋游戏帮助信息\n\n规则：在棋盘上横向、纵向或斜向连续落子，最先形成五个同色棋子的一方获胜。");
}

void MainWindow::onAboutActionTriggered() {
    QMessageBox::about(this, "关于五子棋", "五子棋游戏\n版本 1.0\n\n这是一个简单的五子棋游戏实现，使用Qt框架开发。");
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    //绘制棋盘
    painter.setRenderHint(QPainter::Antialiasing,true);//抗锯齿

    for(int i = 0;i<BOARD_GRAD_SIZE + 1;i++)
    {
        //从左到右，第（i+1）条竖线
        painter.drawLine(MARGIN + BLOCK_SIZE * i,MARGIN,MARGIN + BLOCK_SIZE * i,size().height() - MARGIN);
        //从上到下，第（i+1）条横线
        painter.drawLine(MARGIN,MARGIN + BLOCK_SIZE * i,size().width() - MARGIN,MARGIN + BLOCK_SIZE * i);
    }

    //绘制选中点
    QBrush brush;
    brush.setStyle(Qt::SolidPattern);
    //绘制落子标记（防止鼠标出框越界）
    if(clickPosRow > 0 && clickPosRow < BOARD_GRAD_SIZE && clickPosCol > 0 && clickPosCol < BOARD_GRAD_SIZE && game->gameMapVec[clickPosRow][clickPosCol]==0)
    {
        if(game->playerFlag)
        {
            brush.setColor(Qt::black);
        }
        else
        {
            brush.setColor(Qt::white);
        }
        painter.setBrush(brush);
        painter.drawRect(MARGIN + BLOCK_SIZE * clickPosCol - MARK_SIZE / 2, MARGIN + BLOCK_SIZE * clickPosRow - MARK_SIZE / 2,MARK_SIZE,MARK_SIZE);
    }

    //绘制棋子
    for(int i = 0;i < BOARD_GRAD_SIZE;i++)
    {
        for(int j = 0;j < BOARD_GRAD_SIZE;j++)
        {
            if(game->gameMapVec[i][j] == 1)
            {
                //brush.setColor(Qt::white);
                brush.setColor(Qt::black);

                painter.setBrush(brush);
                painter.drawEllipse(MARGIN + BLOCK_SIZE * j - CHESS_RADIUS,MARGIN + BLOCK_SIZE * i - CHESS_RADIUS,2 * CHESS_RADIUS,2 * CHESS_RADIUS);
            }
            else if(game->gameMapVec[i][j] == -1)
            {
                //brush.setColor(Qt::black);
                brush.setColor(Qt::white);

                painter.setBrush(brush);
                painter.drawEllipse(MARGIN + BLOCK_SIZE * j - CHESS_RADIUS,MARGIN + BLOCK_SIZE * i - CHESS_RADIUS,2 * CHESS_RADIUS,2 * CHESS_RADIUS);
            }
        }
    }

    //判断输赢
    if(clickPosRow > 0 && clickPosRow < BOARD_GRAD_SIZE && clickPosCol > 0 && clickPosCol < BOARD_GRAD_SIZE && (game->gameMapVec[clickPosRow][clickPosCol] == 1 ||game->gameMapVec[clickPosRow][clickPosCol] == -1))
    {
        if(game->isWin(clickPosRow,clickPosCol) && game->gameStatus == PLAYING)
        {
            //qDebug<<"胜利！";
            game->gameStatus = WIN;
            //QSound::play(":sound/win.wav");
            QString str;
            if(game->gameMapVec[clickPosRow][clickPosCol] == 1)
            {
                str = "黑棋";
            }
            else if(game->gameMapVec[clickPosRow][clickPosCol] == -1)
            {
                str = "白棋";
            }
            QMessageBox::StandardButton btnValue = QMessageBox::information(this,"五子棋决战",str + "胜利！");

            //重置游戏状态，否则容易死循环
            if(btnValue == QMessageBox::Ok)
            {
                game->startGame(game_type);
                game->gameStatus = PLAYING;
                // 重置游戏状态
                humanVsAIButton->show();
                humanVsHumanButton->show();
                settingsButton->show();
                helpButton->show();
                titleLabel->show();
            }
        }
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    //通过鼠标的hover确定落子的标记
    int x = event->x();
    int y = event->y();

    //棋盘的边缘不能落子
    if(x >= MARGIN + BLOCK_SIZE / 2 && x < size().width() - MARGIN - BLOCK_SIZE / 2 && y >= MARGIN + BLOCK_SIZE / 2 && y < size().height() - MARGIN - BLOCK_SIZE / 2)
    {
        //获取最近的左上角的点
        //add by rock
        int col = (x - MARGIN) / BLOCK_SIZE;
        int row = (y - MARGIN) / BLOCK_SIZE;
        //int col = x / kBlockSize;
        //int row = y / kBlockSize;

        int leftTopPosX = MARGIN + BLOCK_SIZE * col;
        int leftTopPosY = MARGIN + BLOCK_SIZE * row;

        //根据距离算出合适的点击位置，一共四个点，根据半径距离选最近的
        clickPosRow = -1;  //初始化最终的值
        clickPosCol = -1;
        int len = 0;//计算完取整

        selectPos = false;

        //确定一个误差在范围内的点，且只可能确定一个出来
        len = sqrt((x - leftTopPosX) * (x - leftTopPosX) + (y - leftTopPosY) * (y - leftTopPosY));
        if(len < POS_OFFSET)
        {
            clickPosRow = row;
            clickPosCol = col;
            if(game->gameMapVec[clickPosRow][clickPosCol]==0)
            {
                selectPos = true;
            }
        }

        len = sqrt((x - leftTopPosX - BLOCK_SIZE) * (x - leftTopPosX - BLOCK_SIZE) + (y - leftTopPosY) * (y - leftTopPosY));
        if(len < POS_OFFSET)
        {
            clickPosRow = row;
            clickPosCol = col + 1;
            if(game->gameMapVec[clickPosRow][clickPosCol]==0)
            {
                selectPos = true;
            }
        }

        len = sqrt((x - leftTopPosX) * (x - leftTopPosX) + (y - leftTopPosY - BLOCK_SIZE) * (y - leftTopPosY - BLOCK_SIZE));
        if(len < POS_OFFSET)
        {
            clickPosRow = row + 1;
            clickPosCol = col;
            if(game->gameMapVec[clickPosRow][clickPosCol]==0)
            {
                selectPos = true;
            }
        }

        len = sqrt((x - leftTopPosX - BLOCK_SIZE) * (x - leftTopPosX - BLOCK_SIZE) + (y - leftTopPosY - BLOCK_SIZE) * (y - leftTopPosY - BLOCK_SIZE));
        if(len < POS_OFFSET)
        {
            clickPosRow = row + 1;
            clickPosCol = col + 1;
            if(game->gameMapVec[clickPosRow][clickPosCol]==0)
            {
                selectPos = true;
            }
        }
    }

    //存了坐标后也要重绘
    update();
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if(selectPos == false)
    {
        return;
    }
    else
    {
        //在落子之前，把落子标记再设置为false
        selectPos = false;
    }

    //由人来下棋
    chessOneByPerson();

    if(game_type == AI)
    {
        //人机模式
        //AI下棋
        QTimer::singleShot(AI_THINK_TIME,this,SLOT(chessOneByAI()));
    }
}

void MainWindow::chessOneByPerson()
{
    //根据当前存储的坐标下子
    //只有有效点击才下子，并且该处没有子
    if(clickPosRow != -1 && clickPosCol != -1 && game->gameMapVec[clickPosRow][clickPosCol] == 0)
    {
        //在游戏的数据模型中落子
        game->actionByPerson(clickPosRow,clickPosCol);
        //重绘
        update();
    }
}

void MainWindow::chessOneByAI()
{
    game->actionByAI(clickPosRow,clickPosCol);
    update();
}

void MainWindow::onNewGameActionTriggered()
{
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "重新开始", "您确定要重新开始游戏吗？",
                                  QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        // 调用重置游戏的函数
        initGame();  // 你可以调用你原本的 `initGame()` 函数来重置游戏
        // 如果是人机模式，重新开始人机对战
        if (game_type == AI) {
            initAIGame();
        } else {
            initHumanVsHumanGame();
        }
        statusBar()->showMessage("游戏重新开始！", 3000);
    }
}

